package su.myspringbootprojects.springsecuritylearn;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import su.myspringbootprojects.springsecuritylearn.entity.ApplicationUser;
import su.myspringbootprojects.springsecuritylearn.entity.Roles;
import su.myspringbootprojects.springsecuritylearn.repository.RoleRepository;
import su.myspringbootprojects.springsecuritylearn.repository.UserRepository;

/**
 * Класс DatabaseUtilityRunner
 * <p/>
 * Создает пользователей и роли и заполняет ими соответствующую БД
 * <p/>
 *
 * @author petr.mikhailin
 * created 03.07.2024 8:26
 */
@Component
public class DatabaseUtilityRunner implements CommandLineRunner {
    private final UserRepository userRepository;

    private final RoleRepository roleRepository;

    private final PasswordEncoder passwordEncoder;

    @Autowired
    public DatabaseUtilityRunner(UserRepository userRepository, RoleRepository roleRepository, PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.roleRepository = roleRepository;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public void run(String... args) {
        try {
            Roles userRole = new Roles();
            userRole.setRoleName("USER");
            Roles adminRole = new Roles();
            adminRole.setRoleName("ADMIN");
            roleRepository.save(userRole);
            roleRepository.save(adminRole);

            ApplicationUser user1 = new ApplicationUser();
            user1.setFirstName("Sedayko Stumchik");
            user1.setEmail("sedayko_stumchik@drugs.com");
            user1.setPassword(passwordEncoder.encode("123456"));
            user1.setRole(userRole);

            ApplicationUser adminUser = new ApplicationUser();
            adminUser.setFirstName("Semar Zdrahar");
            adminUser.setEmail("semar_zdrahar@drugs.com");
            adminUser.setPassword(passwordEncoder.encode("12345"));
            adminUser.setRole(adminRole);

            userRepository.save(user1);
            userRepository.save(adminUser);
        } catch (Exception ignored) { }
    }
}